import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';

// 订单状态类型
type OrderStatus = 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled';

// 订单项接口
interface OrderItem {
  id: string;
  productId: string;
  title: string;
  price: number;
  quantity: number;
  image: string;
}

// 订单接口
interface Order {
  id: string;
  orderNumber: string;
  items: OrderItem[];
  totalAmount: number;
  status: OrderStatus;
  createdAt: string;
  paymentMethod: string;
  shippingAddress: string;
}

// 订单状态文本和颜色映射
const statusConfig = {
  'pending': { text: '待支付', color: 'text-yellow-500', bgColor: 'bg-yellow-100 dark:bg-yellow-900/30' },
  'paid': { text: '已支付', color: 'text-blue-500', bgColor: 'bg-blue-100 dark:bg-blue-900/30' },
  'shipped': { text: '已发货', color: 'text-purple-500', bgColor: 'bg-purple-100 dark:bg-purple-900/30' },
  'delivered': { text: '已完成', color: 'text-green-500', bgColor: 'bg-green-100 dark:bg-green-900/30' },
  'cancelled': { text: '已取消', color: 'text-red-500', bgColor: 'bg-red-100 dark:bg-red-900/30' }
};

// 模拟订单数据
const mockOrders: Order[] = [
  {
    id: '1',
    orderNumber: '202310300001',
    items: [
      {
        id: 'item-1',
        productId: '1',
        title: '九成新 MacBook Pro 2023',
        price: 8999,
        quantity: 1,
        image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=laptop%20macbook%20pro%20new%20condition&sign=20f4f73de7dc224e47978f4a391ca9b9'
      }
    ],
    totalAmount: 8999,
    status: 'paid',
    createdAt: '2023-10-30 10:30:00',
    paymentMethod: '微信支付',
    shippingAddress: '主校区学生公寓A栋'
  },
  {
    id: '2',
    orderNumber: '202310290002',
    items: [
      {
        id: 'item-2',
        productId: '2',
        title: '大学英语四级词汇书',
        price: 25,
        quantity: 2,
        image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=english%20vocabulary%20book%20for%20exam&sign=69084fa9b4b4f62bc00931f403d1340b'
      },
      {
        id: 'item-3',
        productId: '5',
        title: '考研政治复习资料全套',
        price: 120,
        quantity: 1,
        image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=postgraduate%20entrance%20exam%20political%20study%20materials&sign=ff90125a8a72b3ed5135015226dc85fb'
      }
    ],
    totalAmount: 170,
    status: 'delivered',
    createdAt: '2023-10-29 15:45:00',
    paymentMethod: '支付宝',
    shippingAddress: '东校区图书馆'
  },
  {
    id: '3',
    orderNumber: '202310280003',
    items: [
      {
        id: 'item-4',
        productId: '4',
        title: '篮球装备套装',
        price: 199,
        quantity: 1,
        image: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=basketball%20equipment%20set%20with%20ball%20and%20shoes&sign=c7c0864626ca8ad7c63c6063a27ea339'
      }
    ],
    totalAmount: 199,
    status: 'pending',
    createdAt: '2023-10-28 09:15:00',
    paymentMethod: '未支付',
    shippingAddress: '南校区体育馆'
  }
];

export default function OrderList() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [filteredOrders, setFilteredOrders] = useState<Order[]>([]);
  const navigate = useNavigate();
  const { theme } = useTheme();

  // 加载订单数据
  useEffect(() => {
    // 模拟API请求
    setTimeout(() => {
      setOrders(mockOrders);
      setFilteredOrders(mockOrders);
    }, 500);
  }, []);

  // 按状态筛选订单
  useEffect(() => {
    if (selectedStatus === 'all') {
      setFilteredOrders(orders);
    } else {
      setFilteredOrders(orders.filter(order => order.status === selectedStatus));
    }
  }, [selectedStatus, orders]);

  // 取消订单
  const cancelOrder = (orderId: string) => {
    if (window.confirm('确定要取消该订单吗？')) {
      const updatedOrders = orders.map(order => 
        order.id === orderId ? { ...order, status: 'cancelled' as OrderStatus } : order
      );
      setOrders(updatedOrders);
      toast.success('订单已取消');
    }
  };

  // 支付订单
  const payOrder = (orderId: string) => {
    const updatedOrders = orders.map(order => 
      order.id === orderId ? { ...order, status: 'paid' as OrderStatus, paymentMethod: '微信支付' } : order
    );
    setOrders(updatedOrders);
    toast.success('支付成功');
  };

  // 确认收货
  const confirmDelivery = (orderId: string) => {
    if (window.confirm('确认已收到商品吗？')) {
      const updatedOrders = orders.map(order => 
        order.id === orderId ? { ...order, status: 'delivered' as OrderStatus } : order
      );
      setOrders(updatedOrders);
      toast.success('已确认收货');
    }
  };

  // 获取订单操作按钮
  const getOrderActions = (order: Order) => {
    switch (order.status) {
      case 'pending':
        return (
          <>
            <button
              onClick={() => payOrder(order.id)}
              className="px-3 py-1 text-xs bg-indigo-600 dark:bg-indigo-500 text-white rounded hover:bg-indigo-700 dark:hover:bg-indigo-600 mr-2"
            >
              立即支付
            </button>
            <button
              onClick={() => cancelOrder(order.id)}
              className="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              取消订单
            </button>
          </>
        );
      case 'paid':
        return (
          <button
            className="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            查看物流
          </button>
        );
      case 'shipped':
        return (
          <button
            onClick={() => confirmDelivery(order.id)}
            className="px-3 py-1 text-xs bg-indigo-600 dark:bg-indigo-500 text-white rounded hover:bg-indigo-700 dark:hover:bg-indigo-600"
          >
            确认收货
          </button>
        );
      case 'delivered':
        return (
          <button
            className="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            再次购买
          </button>
        );
      case 'cancelled':
        return (
          <button
            className="px-3 py-1 text-xs border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded hover:bg-gray-50 dark:hover:bg-gray-700"
          >
            删除订单
          </button>
        );
      default:
        return null;
    }
  };

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900 py-8 px-4 sm:px-6 lg:px-8")}>
      <div className="max-w-5xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">我的订单</h1>
        </div>
        
        {/* 订单状态筛选 */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-4 mb-6">
          <div className="flex flex-wrap gap-2">
            <button
              onClick={() => setSelectedStatus('all')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedStatus === 'all'
                  ? 'bg-indigo-100 dark:bg-indigo-900 text-indigo-600 dark:text-indigo-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              全部订单
            </button>
            <button
              onClick={() => setSelectedStatus('pending')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedStatus === 'pending'
                  ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 dark:text-yellow-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              待支付
            </button>
            <button
              onClick={() => setSelectedStatus('paid')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedStatus === 'paid'
                  ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              已支付
            </button>
            <button
              onClick={() => setSelectedStatus('shipped')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedStatus === 'shipped'
                  ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              已发货
            </button>
            <button
              onClick={() => setSelectedStatus('delivered')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedStatus === 'delivered'
                  ? 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              已完成
            </button>
            <button
              onClick={() => setSelectedStatus('cancelled')}
              className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                selectedStatus === 'cancelled'
                  ? 'bg-red-100 dark:bg-red-900/30 text-red-600 dark:text-red-400'
                  : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              已取消
            </button>
          </div>
        </div>
        
        {/* 订单列表 */}
        {filteredOrders.length === 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-8 text-center">
            <div className="inline-flex items-center justify-center p-6 rounded-full bg-gray-100 dark:bg-gray-700 mb-4">
              <i className="fa-solid fa-file-invoice text-3xl text-gray-400"></i>
            </div>
            <h3 className="text-xl font-medium text-gray-900 dark:text-white mb-2">暂无订单</h3>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              {selectedStatus === 'all' 
                ? '您还没有任何订单，快去选购商品吧' 
                : `暂无${statusConfig[selectedStatus as OrderStatus]?.text}的订单`}
            </p>
            <Link
              to="/"
              className="px-6 py-2 rounded-lg text-white bg-indigo-600 dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600 text-sm font-medium"
            >
              去购物
            </Link>
          </div>
        ) : (
          <div className="space-y-6">
            {filteredOrders.map((order) => (
              <div key={order.id} className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm overflow-hidden">
                {/* 订单头部信息 */}
                <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex flex-col md:flex-row md:items-center justify-between">
                  <div className="flex flex-wrap items-center gap-4 mb-3 md:mb-0">
                    <div className="flex items-center">
                      <span className="text-sm text-gray-600 dark:text-gray-400 mr-2">订单编号:</span>
                      <span className="text-sm font-medium text-gray-900 dark:text-white">{order.orderNumber}</span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-sm text-gray-600 dark:text-gray-400 mr-2">下单时间:</span>
                      <span className="text-sm text-gray-900 dark:text-white">{order.createdAt}</span>
                    </div>
                  </div>
                  
                  <div className="flex items-center justify-between w-full md:w-auto">
                    <div className={`px-3 py-1 rounded-full text-xs font-medium ${statusConfig[order.status].bgColor} ${statusConfig[order.status].color}`}>
                      {statusConfig[order.status].text}
                    </div>
                    
                    {/* 订单操作按钮 */}
                    <div className="mt-3 md:mt-0 md:ml-4">
                      {getOrderActions(order)}
                    </div>
                  </div>
                </div>
                
                {/* 订单项 */}
                <div className="px-6 py-4">
                  {order.items.map((item) => (
                    <div key={item.id} className="flex items-center py-3 border-b border-gray-100 dark:border-gray-700 last:border-0">
                      <div className="w-20 h-20 flex-shrink-0 bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden">
                        <img 
                          src={item.image} 
                          alt={item.title}
                          className="w-full h-full object-cover"
                        />
                      </div>
                      <div className="ml-4 flex-1">
                        <Link 
                          to={`/product/${item.productId}`}
                          className="text-sm text-gray-900 dark:text-gray-100 hover:text-indigo-600 dark:hover:text-indigo-400 line-clamp-1"
                        >
                          {item.title}
                        </Link>
                        <div className="mt-1 flex items-center justify-between">
                          <span className="text-sm text-gray-500 dark:text-gray-400">
                            x{item.quantity}
                          </span>
                          <span className="text-sm font-medium text-gray-900 dark:text-white">
                            ¥{item.price}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                
                {/* 订单底部信息 */}
                <div className="px-6 py-4 bg-gray-50 dark:bg-gray-750 flex flex-col sm:flex-row sm:items-center justify-between">
                  <div className="text-sm text-gray-600 dark:text-gray-400 mb-3 sm:mb-0">
                    收货地址: {order.shippingAddress}
                  </div>
                  <div className="flex items-center">
                    <span className="text-sm text-gray-600 dark:text-gray-400 mr-2">实付金额:</span>
                    <span className="text-lg font-bold text-red-600 dark:text-red-400">
                      ¥{order.totalAmount}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}